//
//  XMScrollViewImage.m
//  XMScrollViewImage
//
//  Created by chenming on 2018/5/17.
//  Copyright © 2018年 ChenXiaoMing. All rights reserved.
//

#import "XMScrollViewImage.h"

// View
#import "XMScrollViewImageCell.h"

static NSString *const cellIdentifier = @"cellIdentifier";

static const NSTimeInterval kAnimationDuration = 2;

@interface XMScrollViewImage ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSArray *reloadArray;

@property (nonatomic, assign) NSInteger currentItem;

@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation XMScrollViewImage

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _currentItem = 1;
        [self addSubview:self.collectionView];
        [self addSubview:self.pageControl];
        [self timer];
    }
    return self;
}

- (void)setDataUrlSources:(NSArray *)dataUrlSources {
    if (![dataUrlSources isKindOfClass:[NSArray class]]) return;
    _dataUrlSources = dataUrlSources;
    self.reloadArray = [self reloadDataArrayWithDataArray:dataUrlSources];
    [self setNeedsLayout];
    if (_reloadArray.count > 1) {
        dispatch_async(dispatch_get_main_queue(), ^{ // 异步主线程执行
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_currentItem inSection:0]
                                        atScrollPosition:UICollectionViewScrollPositionNone
                                                animated:NO];
            self.pageControl.numberOfPages = self.reloadArray.count - 2;
        });
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self reloadItemScrollImageAction];
    
    [self timer];
}

- (void)removeTimer {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    [self.timer invalidate];
    self.timer = nil;
}

/**
 * 如果图片数据源[1.jpg,2.jpg,3.jpg,4.jpg],则对数据进行操作修改,达成[4.jpg,1.jpg,2.jpg,3.jpg,4.jpg,1.jpg]
 */
- (NSArray *)reloadDataArrayWithDataArray:(NSArray *)dataArray {
    NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:dataArray.count];
    [resultArray addObject:dataArray.lastObject];
    for (id object in dataArray) {
        [resultArray addObject:object];
    }
    [resultArray addObject:dataArray.firstObject];
    return resultArray;
}

- (void)timerAnimationChange {
    if (self.currentItem == self.reloadArray.count - 2) {
        NSInteger toItem = 0;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:toItem inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                            atScrollPosition:UICollectionViewScrollPositionNone
                                                    animated:NO];
        self.currentItem = toItem;
    }
    
    self.currentItem ++;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentItem inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath
                                        atScrollPosition:UICollectionViewScrollPositionLeft
                                                animated:YES];
    self.pageControl.currentPage = self.currentItem - 1;
}

// 显示正确位置
- (void)reloadItemScrollImageAction {
    NSIndexPath *indexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    self.currentItem = indexPath.item;
    NSInteger toItem = 0;
    
    if (self.currentItem == 0) {
        toItem = self.reloadArray.count - 2;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:toItem inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                            atScrollPosition:UICollectionViewScrollPositionNone
                                                    animated:NO];
        self.currentItem = toItem;
    }
    
    if (self.currentItem == self.reloadArray.count - 1) {
        toItem = 1;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:toItem inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                            atScrollPosition:UICollectionViewScrollPositionNone
                                                    animated:NO];
        self.currentItem = toItem;
    }
    
    self.pageControl.currentPage = self.currentItem - 1;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.collectionView.frame = self.bounds;
    self.pageControl.frame = CGRectMake((CGRectGetWidth(self.frame) - 100) / 2, CGRectGetHeight(self.frame) - 20, 100, 20);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.reloadArray.count == 1 ? 1 : self.reloadArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *gridcell = nil;
    XMScrollViewImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell.scrollImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.reloadArray[indexPath.item]]] placeholderImage:nil];
    gridcell = cell;
    return gridcell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (NSTimer *)timer {
    if (!_timer) {
       _timer = [NSTimer timerWithTimeInterval:kAnimationDuration
                                             target:self
                                           selector:@selector(timerAnimationChange)
                                           userInfo:nil
                                            repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer
                                     forMode:NSRunLoopCommonModes];
    }
    return _timer;
}

- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        _pageControl.currentPage = 0;
        _pageControl.defersCurrentPageDisplay = YES;
        _pageControl.currentPageIndicatorTintColor = [UIColor colorWithHexString:@"00bfff" alpha:1];
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    }
    return _pageControl;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.bounces = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[XMScrollViewImageCell class] forCellWithReuseIdentifier:cellIdentifier];
    }
    return _collectionView;
}

@end
